package handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import constant.Constants;
import model.CustomerSessions;
import model.StakeManager;
import util.ResponseUtil;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 管理三个路径的请求
 * @Author admin
 * @Date 2025-1-7 11:36
 */
public class BettingOfferManagerHandler implements HttpHandler {

    private final SessionHandler sessionHandler;
    private final StakeHandler stakeHandler;
    private final HighStakeHandler highStakeHandler;

    public BettingOfferManagerHandler(CustomerSessions customerSessions, StakeManager stakeManager) {
        this.sessionHandler = new SessionHandler(customerSessions);
        this.stakeHandler = new StakeHandler(customerSessions, stakeManager);
        this.highStakeHandler = new HighStakeHandler(stakeManager);
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String requestURI = exchange.getRequestURI().getPath();
        String requestMethod = exchange.getRequestMethod();
        try {
            Matcher sessionMatcher = Constants.GET_SESSION_PATH_PATTERN.matcher(requestURI);
            Matcher stakeMatcher = Constants.STAKE_PATH_PATTERN.matcher(requestURI);
            Matcher highstakeMatcher = Constants.HIGH_STAKE_PATH_PATTERN.matcher(requestURI);

            if (sessionMatcher.matches() && Constants.GET.equals(requestMethod)) {
                sessionHandler.doHandler(sessionMatcher.group(1), exchange);
            } else if (stakeMatcher.matches() && Constants.POST.equals(requestMethod)) {
                stakeHandler.doHandler(stakeMatcher.group(1), exchange);
            } else if (highstakeMatcher.matches() && Constants.GET.equals(requestMethod)) {
                highStakeHandler.doHandler(highstakeMatcher.group(1), exchange);
            } else {
                ResponseUtil.sendErrorResponse(exchange, Constants.INVALID_CODE, "Invalid request method or format");
            }
        } catch (IllegalArgumentException e) {
            // 处理正则表达式匹配失败或参数解析错误
            ResponseUtil.sendErrorResponse(exchange, Constants.INVALID_CODE, "Invalid request format: " + e.getMessage());
        } catch (Exception e) {
            // 处理其他未预期的异常
            ResponseUtil.sendErrorResponse(exchange, Constants.INVALID_CODE, "Internal server error: " + e.getMessage());
        }
    }
}